from drf_spectacular.utils import extend_schema, inline_serializer
from rest_framework import status as ResponseStatus
from rest_framework.decorators import action
from rest_framework.mixins import (CreateModelMixin, ListModelMixin,
                                   RetrieveModelMixin, UpdateModelMixin)
from rest_framework.viewsets import GenericViewSet
from backend.cews.services import ReportService
from utils.autoschema import AutoDocSchema, custom_response_serailizer
from utils.decorators import request_data

from .serializers import (RepairOrderSerializer)
from rest_framework.response import Response
from rest_framework import serializers
from datetime import timedelta
from django.utils import timezone
import csv


class ReportViewSet(
    RetrieveModelMixin,
    ListModelMixin,
    UpdateModelMixin,
    GenericViewSet,
    CreateModelMixin
):

    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["stock_code","equipment_class","level","location","dateFrom","dateTo"],optional=["stock_code","equipment_class","level","location","dateFrom","dateTo"])
    def repair_order_history(self, request, stock_code,equipment_class,level,location,dateFrom,dateTo):
        print(level)
        results = ReportService.repair_order_history(stock_code,equipment_class,level,location,dateFrom,dateTo)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        })

    @action(detail=False, methods=['get'], schema=AutoDocSchema())
    def repair_order_nff_records(self, request):
       
        results = ReportService.repair_order_nff_records()

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 

    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["system", "year"], types={"system": str, "year": str})
    def repair_order_detail_overview(self, request, system, year):
        
        results = ReportService.repair_order_detail_overview(system, year)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 

    @action(detail=False, methods=['get'], schema=AutoDocSchema())
    def inout_summary(self, request):
        
        results = ReportService.inout_summary()

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 

    @action(detail=False, methods=['get'], schema=AutoDocSchema())
    def registration_summary(self, request):
        
        results = ReportService.registration_summary()

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 
    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["year", "month"], types={"year": str, "month": str})
    def outgoing_record(self, request, year, month):
        
        results = ReportService.outgoing_record(year,month)
        RepairOrderSerializer()
        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 
    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["year", "month"], types={"year": str, "month": str})
    def chart_repair_time_of_various_workgroup(self, request, year, month):
        """分组查询workgroup

        Args:
            request (_type_): _description_
            year (_type_): 年份
            month (_type_): 月份
        """
        results = ReportService.chart_repair_time_of_various_workgroup(year, month)
        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        })   
    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["repair_detail","system", "year"], types={"repair_detail":str,"system": str, "year": str})
    def repair_order_detail_table(self, request,repair_detail, system, year):
        
        results = ReportService.repair_order_detail_table(repair_detail, system, year)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 
    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["year", "month"], types={"year": str, "month": str})
    def get_spare_availability(self, request, year, month):
        
        results = ReportService.get_spare_availability(year,month)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 

    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["year", "month"], types={"year": str, "month": str})
    def get_overhaul_index(self, request, year, month):
        
        results = ReportService.get_overhaul_index(year, month)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 

    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["year", "month"], types={"year": str, "month": str})
    def get_long_outstanding(self, request, year, month):
        
        results = ReportService.get_long_outstanding(year, month)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 
    
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["year", "month"], types={"year": str, "month": str})
    def repair_performance_summary(self, request, year, month):
        
        results = ReportService.repair_performance_summary(year, month)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 
    

    @action(detail=False, methods=['get'], schema=AutoDocSchema())
    def get_critical_hard_time_replacement(self, request):
        
        results = ReportService.get_critical_hard_time_replacement(request.user)

        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        }) 
    

    @action(detail=False, methods=['get'], schema=AutoDocSchema())
    def get_mean_time_between_failure(self, request):

        today = timezone.now()
        one_year_ago = today - timedelta(days=365)

        results = ReportService.get_mean_time_between_failure(one_year_ago)
        
        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        })
 
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=["stock_code", "serial_no", "system", "work_group", "location"], types={"stock_code": str, "serial_no": str, "system": str, "work_group": str, "location": str})
    def get_spare_location_report(self, request, serial_no, stock_code, system, work_group, location):
        """
        Stock Code, Serial No, System, Work Group, Location
        """
        results = ReportService.get_spare_location_report(stock_code,serial_no ,system, work_group, location)
        return Response(status=200,
                        data={
                            'code': 1,
                            'data': results
                        })
    
    @action(detail=False, methods=["post"], schema=AutoDocSchema())
    @request_data(keys=["parent_work_order_no","start_date", "end_date"], types={"parent_work_order_no": str, "start_date": str, "end_date":str})
    def get_incident_view(self, request,parent_work_order_no,start_date,end_date ):
        try:
            return ReportService.get_incident_view(parent_work_order_no, start_date, end_date)
        except ValueError as e:
            return Response(status=500, data = {"code": 0, "message": str(e)}, content_type='application/json')
       

    @action(detail=False, methods=["post"], schema=AutoDocSchema())
    def upload_incident_view(self, request):

        reader, err = ReportService.check_upload_csv_file(request)
        if err != None:
            return Response(status=200, data={"code": 0, "message": err}, content_type='application/json')
        res, err = ReportService.upload_Incident_view(reader)
        if err != None:
            return Response(status=200, data= {"code": -2,"message": err}, content_type='application/json')
        return Response(status=200, data={
            "code": 1,
            "data": {"update_count": res}
        })
    
    @action(detail=False, methods=["post"], schema=AutoDocSchema())
    @request_data(keys=["parent_work_order_no","report_date"], types={"parent_work_order_no": str, "report_date": str})
    def get_cm_weekly_summary(self, request,parent_work_order_no, report_date):
        try:
            resp = ReportService.get_cm_weekly_summary(parent_work_order_no, report_date)
        except ValueError as e:
            return Response(status=500, data = {"code": 0, "message": str(e)}, content_type='application/json')
        return resp
    
    @action(detail=False, methods=["post"], schema=AutoDocSchema())
    def upload_cm_weekly_summary(self, request):
        reader, err = ReportService.check_upload_csv_file(request)
        if err != None:
            return Response(status=200, data={"code": 0, "message": err})
        res, err = ReportService.upload_cm_weekly_summary(reader)
        if err != None:
            return Response(status=200, data= {"code": -2,"message": err})
        return Response(status=200, data={
            "code": 1,
            "data": {"update_count": res}
        })

    
    @action(detail=False, methods=["post"], schema=AutoDocSchema())
    @request_data(keys=["stock_code","start_date", "end_date", "completed"], types={"stock_code": str,"start_date": str, "end_date": str, "completed": bool})
    def get_igi_report(self, request,stock_code, start_date, end_date, completed):
        """
           start_date到end_date范围, 查询check_in
           completed=1查询check_out不为空
        """
        return ReportService.get_igi_report(stock_code, start_date, end_date,completed, request.user.username)

    @action(detail=False, methods=["post"], schema=AutoDocSchema())
    @request_data(keys=["serial_no","stock_code", "description", "cycle_month", "incoming_cycle_month"], types={"serial_no": str,"stock_code": str, "description": str, "cycle_month": str, "incoming_cycle_month": str})
    def get_regular_check_management_eg_card_with_battery_report(self, request,serial_no,stock_code, description, cycle_month, incoming_cycle_month):
        if cycle_month == "":
            cycle_month = 0
        
        if incoming_cycle_month == "":
            incoming_cycle_month = 0

        results = ReportService.get_regular_check_management_eg_card_with_battery_report(serial_no, stock_code, description, int(cycle_month), int(incoming_cycle_month))
        return Response(
            status=200,
            data={
                'code': 1,
                'data': results
            }
        )